import { useRoutes, useLocation, useNavigate } from "react-router-dom"
import { useEffect, useMemo } from "react"
const useRouteWithGuard = (key, routes) => {
    let token = localStorage.getItem(key)
    let location = useLocation()
    let navigate = useNavigate()
    let Element = useRoutes(routes)
    // console.log(123)
    useEffect(() => {
        if (!token) {
            if (location.pathname !== "/login") {
                navigate('/login')
            }
        }
    }, [location])

    // 通过useMemo处理,解决闪烁的问题 

    // 闪烁的问题 以为组件更新,每次都返回一个新的路由配置,需要重新加载,导致闪烁的问题 
    // 使用useMemo来缓存路由配置
    // Element = useMemo(() => Element, [])
    return Element;
}


export default useRouteWithGuard